package web.bean;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import web.security.AppUserDetails;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.io.IOException;

/**
 * @author MG
 * @since 25.04.2014
 */
@ManagedBean
@SessionScoped
public class LoginBean {

    AppUserDetails loginUser = null;

    private String loginFailed;

    public void initLoginPage() {
        if ("true".equals(loginFailed)) {
            BeanUtils.addErrorMessage("login_failed_msg");
            loginFailed = null;
        }
    }

    public void login() throws IOException {
        BeanUtils.getExternalContext().dispatch("/do_login");
    }

    public AppUserDetails getLoginUser() {
        if (loginUser == null) {
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (principal != null && principal instanceof AppUserDetails) {
                loginUser = (AppUserDetails) principal;
            }
        }
        return loginUser;
    }

    public boolean hasRole(String role) {
        if (getLoginUser() == null || role == null) {
            return false;
        }
        for (GrantedAuthority authority : getLoginUser().getAuthorities()) {
            if (role.equals(authority.getAuthority())) {
                return true;
            }
        }
        return false;
    }

    public boolean isAdmin() {
        return hasRole("ROLE_ADMIN");
    }

    public boolean isUser() {
        return hasRole("ROLE_USER");
    }

    public void setLoginFailed(String loginFailed) {
        this.loginFailed = loginFailed;
    }

    public String getLoginFailed() {
        return loginFailed;
    }
}
